<template>
  <div class="addPush wfull">
    <a-form-model ref="form" :model="form" :rules="rules" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
      <a-form-model-item label="任务名称" prop="taskName">
        <ZgInput v-model="form.taskName" :disabled="formDisabeld" />
      </a-form-model-item>
      <a-form-model-item label="源数据编码" prop="sourceDatasourceCode">
        <ZgSelect v-model="form.sourceDatasourceCode" :options="sourceDataList" :disabled="formDisabeld" />
      </a-form-model-item>
      <a-form-model-item label="源表名" prop="sourceTableName">
        <ZgSelect
          v-model="form.sourceTableName"
          :options="sourceTableList"
          :disabled="!form.sourceDatasourceCode || formDisabeld"
        />
      </a-form-model-item>
      <a-form-model-item label="目标类型" prop="targetType">
        <ZgSelect v-model="form.targetType" :options="targetTypeList" :disabled="formDisabeld" />
      </a-form-model-item>
      <template v-if="form.targetType === 'database'">
        <a-form-model-item label="目标数据编码">
          <ZgSelect v-model="form.targetDatasourceCode" :options="sourceDataList" :disabled="formDisabeld" />
        </a-form-model-item>
        <a-form-model-item label="目标表名">
          <ZgSelect v-model="form.targetTableName" :options="sourceTableList" :disabled="formDisabeld" />
        </a-form-model-item>
      </template>
      <a-form-model-item label="目标系统名称">
        <ZgInput v-model="form.targetSystemName" :disabled="formDisabeld" />
      </a-form-model-item>
      <a-form-model-item label="推送模式" prop="pushMode">
        <ZgSelect v-model="form.pushMode" :options="pushModeList" :disabled="formDisabeld" @change="pushModeChange" />
      </a-form-model-item>
      <template v-if="form.pushMode === 'increment'">
        <a-form-model-item label="增量字段名">
          <ZgSelect v-model="form.incrementField" :options="incrementFieldList" :disabled="formDisabeld" />
        </a-form-model-item>
        <!-- <a-form-model-item label="最后推送时间" prop="lastPushTime"></a-form-model-item> -->
      </template>
      <a-form-model-item label="调度类型" prop="scheduleType">
        <ZgSelect
          v-model="form.scheduleType"
          :options="scheduleTypeList"
          :disabled="formDisabeld"
          @change="scheduleTypeChange"
        />
      </a-form-model-item>
      <template v-if="form.scheduleType === 'cron'">
        <a-form-model-item label="cron表达式" prop="cronExpression">
          <ZgTextarea v-model.trim="form.cronExpression" :maxLength="1000" :disabled="formDisabeld" />
        </a-form-model-item>
      </template>
      <a-form-model-item label="任务状态">
        <ZgSwitch v-model="form.status" :disabled="formDisabeld" />
      </a-form-model-item>
    </a-form-model>
  </div>
</template>
<script>
export default {
  props: {
    // 表单禁用
    formDisabeld: {
      type: Boolean,
      default: false
    },
    operaType: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      form: {
        taskName: undefined,
        sourceDatasourceCode: undefined,
        sourceTableName: undefined,
        targetType: undefined,
        targetDatasourceCode: undefined,
        targetTableName: undefined,
        targetSystemName: undefined,
        pushMode: undefined,
        incrementField: undefined,
        scheduleType: undefined,
        cronExpression: undefined,
        status: 0
      },
      rules: {
        taskName: [{ required: true, message: '请输入任务名称', trigger: 'change' }],
        pushMode: [{ required: true, message: '请选择推送模式', trigger: 'change' }],
        targetType: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
        scheduleType: [{ required: true, message: '请选择调度类型', trigger: 'change' }],
        sourceDatasourceCode: [{ required: true, message: '请选择源数据编码', trigger: 'change' }],
        sourceTableName: [{ required: true, message: '请选择源表名', trigger: 'change' }],
        cronExpression: [{ validator: this.cronValidate, trigger: 'blur' }]
      },
      // 源数据信息
      sourceDataList: [],
      sourceTableList: [],
      // 网关前缀
      gateWayPrefix: '/zg-datapush',
      targetTypeList: [
        { label: '数据库', value: 'database' },
        { label: '接口', value: 'rest' }
      ],
      pushModeList: [
        { label: '全量', value: 'full' },
        { label: '增量', value: 'increment' }
      ],
      scheduleTypeList: [
        { label: '手动', value: 'manual' },
        { label: '定时', value: 'cron' }
      ],
      // 增量字段名
      incrementFieldList: [],
      // cron表达式模版
      cronTemplate: {}
    }
  },
  components: {},
  computed: {},
  watch: {
    'form.sourceDatasourceCode'(val) {
      if (val) this.getTableDataInSource(val)
    },
    operaType(val) {
      if (val === 'add') this.reset()
    }
  },
  methods: {
    /* eslint-disable */
    // 获取所有可用数据源
    getSourceDataList() {
      this.$http.get(`${this.gateWayPrefix}/datapush/datasourceQuery/list`, {}, (data) => {
        this.sourceDataList = data.map((item) => {
          const { username, code } = item
          return { label: username, value: code }
        })
      })
    },
    // 获取可用数据源编码下的表数据
    getTableDataInSource(code) {
      const { gateWayPrefix } = this
      this.$http.post(`${gateWayPrefix}/datapush/tableStructure/tables`, { code }, (data) => {
        this.sourceTableList = data.map((item) => {
          return { label: item, value: item }
        })
      })
    },
    // 推送模式改变后获取增量字段名
    pushModeChange(data) {
      if (data !== 'increment') return
      this.getIncrementFieldName()
    },
    // 获取增量字段名
    getIncrementFieldName() {
      const { sourceDatasourceCode, sourceTableName } = this.form
      this.$http.post(
        `${this.gateWayPrefix}/datapush/tableStructure/columns`,
        {
          datasourceCode: sourceDatasourceCode,
          tableName: sourceTableName
        },
        (data) => (this.incrementFieldList = data)
      )
    },
    // 调度类型改变后获取cron表达式模版
    scheduleTypeChange(data) {
      if (data !== 'cron') return
      this.getCronTemplate()
    },
    // 获取常用cron表达式模板
    getCronTemplate() {
      this.$http.get(`${this.gateWayPrefix}/datapush/cron/templates`, {}, (data) => {
        Object.assign(this, {
          cronTemplate: data
        })
      })
    },
    // cron表达式校验规则
    cronValidate(rule, value, callback) {
      if (!value.length) callback()
      else {
        this.getCronValidate.then(() => callback()).catch(() => callback(new Error('请输入正确格式的Cron表达式')))
      }
    },
    // 接口验证 cron表达式
    getCronValidate(cronExpression) {
      return new Promise((resolve, reject) => {
        this.$http.post(
          `${this.gateWayPrefix}/datapush/cron/validate`,
          {
            cronExpression
          },
          (data) => {
            if (data) resolve()
            else reject()
          }
        )
      })
    },
    save() {
      return new Promise((resolve) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$http.post(
              `${this.gateWayPrefix}/datapush/task/${this.operaType === 'add' ? 'add' : 'update'}`,
              {
                ...Object.assign(this.form, {
                  status: this.status ? 1 : 0
                })
              },
              () => {
                this.$message.success(`推送任务${this.operaType === 'add' ? '新增' : '编辑'}成功`)
                this.resetFields()
                resolve()
              }
            )
          }
        })
      })
    },
    // 表单重置
    resetFields() {
      this.$refs.form.resetFields()
    },
    reset() {
      Object.assign(this.form, {
        taskName: undefined,
        sourceDatasourceCode: undefined,
        sourceTableName: undefined,
        targetType: undefined,
        targetDatasourceCode: undefined,
        targetTableName: undefined,
        targetSystemName: undefined,
        pushMode: undefined,
        incrementField: undefined,
        scheduleType: undefined,
        cronExpression: undefined,
        status: 0
      })
    }
  },
  created() {
    this.getSourceDataList()
  },
  mounted() {}
}
</script>
<style lang="less" scoped></style>
